package com.sh169.util;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.nutz.log.Log;
import org.nutz.log.Logs;

public class MailUtil {
	
	private static Log log = Logs.getLog(MailUtil.class);
	public static void sendMail(String to,String title,String content){
		String host = ApplicationUtil.getMailHost();
		final String from = ApplicationUtil.getUsername();
		final String password = ApplicationUtil.getPassword();
		// Get system properties
		Properties props = System.getProperties();
		// Setup mail server
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.auth","true");

		// Get session
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from, password);
			}
		});

		// Define message
		MimeMessage message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(from));
		
		message.addRecipient(Message.RecipientType.TO, 
		  new InternetAddress(to));
		message.setSubject(title);
		message.setText(content);
		message.setSentDate(new Date());
		// Send message
		//Transport transport = session.getTransport("smtp");
		//transport.connect(host, "feiyan35488@126.com", "3548834239");
		Transport.send(message);
		} catch (AddressException e) {
			log.error(e);
		} catch (MessagingException e) {
			log.error(e);
		}
	}
	
	public static void main(String[] args) throws ClassNotFoundException {
		Class.forName("com.sh169.util.ApplicationUtil");
		sendMail("feiyan35488@gmail.com", "个哦个啊你好", "谷歌欢迎我吧，我来自126.mail");
	}
}
